package com.example.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.google.gson.JsonObject;

@RestController
public class WechatController {
	
	@Autowired
	private RestTemplate restTemplate;
	
	String ACCESS_TOKEN = "34_abDwHZw-uDdLUk_euMNiq7q5NZeC2MDx9GJdKI6FDqe10zxUW42kyfFnadGjF-0sHh9J_JGiy6lxNS5nowL0KFlaMHJOGdgyD0U9_R0IvyONlD8m-K2SUZM-WmGAD8Gx79DMCK6A52rhm1BALZBbAGARFH";
	
	@PostMapping("/message/custom/send")
	public Object messageCustomSend() {
		String content = "hello-测试数据文本内容<a href='http://www.qq.com'>点击跳链接</a>";
		Map<String,String> resultMap = new HashMap<String, String>();
		resultMap.put("message", "操作成功");
		String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+ACCESS_TOKEN;
		try {
			JsonObject jsonObjectText = new JsonObject();
			jsonObjectText.addProperty("content", content);
			JsonObject jsonObject = new JsonObject();
			jsonObject.addProperty("touser", "oJUHLwGuVtX0Srv9_YyP0c3uDIKY");//openid
			jsonObject.addProperty("msgtype", "text");
			jsonObject.add("text", jsonObjectText);
			System.out.println("参数 : "+jsonObject.toString());
			Map apiResult = restTemplate.postForObject(url, jsonObject.toString(), Map.class);
			System.out.println("接口结果: "+apiResult);
			int errcode = (int)apiResult.get("errcode");
			if(errcode == 0) {
				System.out.println("微信接口执行成功");
			}else {
				System.err.println("微信接口执行失败");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("message", "操作失败，"+e.getMessage());
		}
		
		return resultMap;
	}
	
	/**
	 * 
	 * @return
	 */
	@GetMapping("getcallbackip")
	public Object getcallbackip() {
		
		String url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token="+ACCESS_TOKEN;
		try {
			Map<String,Object> resultMap = restTemplate.getForObject(url, Map.class);
			System.out.println(resultMap);
			return resultMap;
		} catch (Exception e) {
			return e.getMessage();
		}
	}
	

	
	
}
